function getParams(name) {
    let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    let r = location.search.substring(1).match(reg);
    if (r != null) {
        return decodeURIComponent(r[2]);
    }
    return null;
}

$(function () {
    let id = getParams('id');
    if (id) {
        $.ajax({
            type:'get',
            url:'http://localhost:5009/api/UserInfo/Find?id='+id,
            success:function(res){
                $('[name=username]').val(res.name);
                $('[name=sex]').val(res.sex);
                $('[name=CardID]').val(res.idNumber);
                $('[name=num]').val(res.phone);
                $('[name=pwd]').val(res.password);
                $('[name=CarID]').val(res.license);
                $('[name=homeAddress]').val(res.home);
                $('[name=roomID]').val(res.room);
            }
        })
    }
})

function btnSave() {
    let id = getParams('id');
    let name = $('[name = username]').val();
    let sex = $('[name = sex]').val();
    if (sex==0) {
        sex = "男"
    }else{
        sex = "女"
    }
    let idNumber = $('[name = CardID]').val();
    let phone = $('[name=num]').val();
    let password = $('[name=pwd]').val();
    let pwdc = $('[name=pwdc]').val();
    let license = $('[name=CarID]').val();
    let home = $('[name=homeAddress]').val();
    let room = $('[name=roomID]').val();
    console.log(id);
    if (id) {
        $.ajax({
            type:'put',
            url:'http://localhost:5009/api/UserInfo/Update/'+id,
            contentType: 'application/json',
            dataType: 'json',
            data: JSON.stringify({ name, sex, idNumber, phone, password, home, license, room }),
            success:function(res){
                console.log(res);
                alert("修改成功");
            }
        })
    } else {
        if (password === pwdc) {
            $.ajax({
                type: 'post',
                url: 'http://localhost:5009/api/UserInfo/Add',
                contentType: 'application/json',
                dataType: 'json',
                data: JSON.stringify({ name, sex, idNumber, phone, password, home, license, room }),
                success: function (res) {
                    console.log(res);
                    alert("注册成功")
                    // location.href = './login.html'
                }
            })
           } else {
            console.log("两次密码不一样，添加失败");
            alert("两次密码不一样，添加失败")
           }
    }
    // location.href = 'index.html';
}


//取消，则返回列表页
function btnCancel() {
    location.href = '../index.html'
}